#include "remotecontroller.h"
#include <QDebug>
#include <QApplication>
#include <QEvent>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QJsonDocument>
#include <QDateTime>
#include <QHostAddress>

RemoteController::RemoteController(QObject *parent) : QObject(parent),
    udpSocket(nullptr), isEnabledFlag(false), eventCounter(0)
{
    // 设置默认屏幕尺寸
    sourceScreenSize = QSize(1920, 1080);
    targetScreenSize = QSize(1920, 1080);
    
    // 设置默认目标地址
    targetAddress = "127.0.0.1";
    targetPort = 5005;
    
    // 计算坐标转换比例
    scaleX = static_cast<double>(targetScreenSize.width()) / sourceScreenSize.width();
    scaleY = static_cast<double>(targetScreenSize.height()) / sourceScreenSize.height();
}

RemoteController::~RemoteController()
{
    if (isEnabledFlag) {
        disable();
    }
    
    if (udpSocket) {
        udpSocket->deleteLater();
    }
}

bool RemoteController::initialize()
{
    // 创建UDP Socket
    udpSocket = new QUdpSocket(this);
    connect(udpSocket, &QUdpSocket::errorOccurred, this, &RemoteController::onSocketError);
    
    qDebug() << "远程控制器初始化完成，目标地址:" << targetAddress << ":" << targetPort;
    return true;
}

void RemoteController::setSourceScreenSize(const QSize& size)
{
    sourceScreenSize = size;
    scaleX = static_cast<double>(targetScreenSize.width()) / sourceScreenSize.width();
    scaleY = static_cast<double>(targetScreenSize.height()) / sourceScreenSize.height();
}

void RemoteController::setTargetScreenSize(const QSize& size)
{
    targetScreenSize = size;
    scaleX = static_cast<double>(targetScreenSize.width()) / sourceScreenSize.width();
    scaleY = static_cast<double>(targetScreenSize.height()) / sourceScreenSize.height();
}

void RemoteController::setTargetAddress(const QString& address, quint16 port)
{
    targetAddress = address;
    targetPort = port;
    qDebug() << "设置远程控制目标地址:" << address << ":" << port;
}

void RemoteController::enable()
{
    if (isEnabledFlag) {
        return;
    }
    
    qDebug() << "启用远程控制...";
    
    // 安装事件过滤器到应用程序
    QApplication::instance()->installEventFilter(this);
    
    isEnabledFlag = true;
    emit enabled();
    
    qDebug() << "远程控制已启用";
}

void RemoteController::disable()
{
    if (!isEnabledFlag) {
        return;
    }
    
    qDebug() << "禁用远程控制...";
    
    // 移除事件过滤器
    QApplication::instance()->removeEventFilter(this);
    
    isEnabledFlag = false;
    emit disabled();
    
    qDebug() << "远程控制已禁用";
}

bool RemoteController::isEnabled() const
{
    return isEnabledFlag;
}

bool RemoteController::eventFilter(QObject* /*obj*/, QEvent* event)
{
    if (!isEnabledFlag) {
        return false;
    }
    
    QJsonObject command;
    
    switch (event->type()) {
        case QEvent::MouseButtonPress: {
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            command = createMouseEvent(event->type(), mouseEvent->pos(), mouseEvent->button());
            break;
        }
        case QEvent::MouseButtonRelease: {
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            command = createMouseEvent(event->type(), mouseEvent->pos(), mouseEvent->button());
            break;
        }
        case QEvent::MouseMove: {
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            command = createMouseEvent(event->type(), mouseEvent->pos());
            break;
        }
        case QEvent::KeyPress: {
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            command = createKeyEvent(event->type(), keyEvent->key(), keyEvent->modifiers());
            break;
        }
        case QEvent::KeyRelease: {
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            command = createKeyEvent(event->type(), keyEvent->key(), keyEvent->modifiers());
            break;
        }
        default:
            return false;
    }
    
    if (!command.isEmpty()) {
        sendCommand(command);
        emit eventCaptured(QString("事件已捕获: %1").arg(event->type()));
    }
    
    return false; // 不阻止事件继续传播
}

void RemoteController::convertCoordinates(QPoint& point)
{
    point.setX(static_cast<int>(point.x() * scaleX));
    point.setY(static_cast<int>(point.y() * scaleY));
}

void RemoteController::sendCommand(const QJsonObject& command)
{
    if (!udpSocket) {
        return;
    }
    
    QJsonDocument doc(command);
    QByteArray data = doc.toJson();
    
    qint64 bytesSent = udpSocket->writeDatagram(data, QHostAddress(targetAddress), targetPort);
    
    if (bytesSent > 0) {
        emit commandSent(QString("命令已发送: %1 字节").arg(bytesSent));
    } else {
        emit errorOccurred("发送命令失败");
    }
}

QJsonObject RemoteController::createMouseEvent(QEvent::Type type, const QPoint& pos, Qt::MouseButton button)
{
    QPoint convertedPos = pos;
    convertCoordinates(convertedPos);
    
    QJsonObject event;
    event["type"] = "mouse";
    event["eventType"] = static_cast<int>(type);
    event["x"] = convertedPos.x();
    event["y"] = convertedPos.y();
    event["button"] = static_cast<int>(button);
    event["timestamp"] = QDateTime::currentMSecsSinceEpoch();
    event["id"] = ++eventCounter;
    
    return event;
}

QJsonObject RemoteController::createKeyEvent(QEvent::Type type, int key, Qt::KeyboardModifiers modifiers)
{
    QJsonObject event;
    event["type"] = "keyboard";
    event["eventType"] = static_cast<int>(type);
    event["key"] = key;
    event["modifiers"] = static_cast<int>(modifiers);
    event["timestamp"] = QDateTime::currentMSecsSinceEpoch();
    event["id"] = ++eventCounter;
    
    return event;
}

void RemoteController::onSocketError(QAbstractSocket::SocketError error)
{
    QString errorStr = QString("UDP Socket错误: %1").arg(udpSocket->errorString());
    emit errorOccurred(errorStr);
}
